package org.ihelpuoo.weboo.tag;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import org.ihelpuoo.io.FileUtils;
import org.ihelpuoo.lang.ObjectUtils;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.parser.segment.CharSegment;
import org.ihelpuoo.parser.segment.Segment;

public class Main
{
	public static void main(String[] args) throws Exception
	{
		Segment tld = getSegment("tld.seg");
		String tldName = "ajax";
		Package pg = Main.class.getPackage();
		String pn = pg.getName() + "." + tldName;
		File dir = FileUtils.findFile("org/ihelpuoo/weboo/tag/" + tldName);
		File[] fs = dir.listFiles();
		for (int i = 0; i < fs.length; i++)
		{
			String name = fs[i].getName();
			if (!name.endsWith("Tag.class"))
				continue;
			Segment tag = getSegment("tag.seg");

			Class type = Class.forName(pn + "." + name.substring(0,name.length() - 6));
			if (Modifier.isAbstract(type.getModifiers()))
				continue;
			name = StringUtils.firstLowercase(name.substring(0,name.length() - 9));
			tag.clearAll();
			tag.set("name",name);
			tag.set("class",type.getName());
			Field[] fields = ObjectUtils.getAllMyStdFields(type);
			for (int z = 0; z < fields.length; z++)
			{
				Segment att = getSegment("att.seg");
				Field f = fields[z];
				if (f.getType() != String.class || f.getName().equals("id"))
					continue;
				tag.add("atts",att.set("name",f.getName()).set("required",
						!"paramName".equals(f.getName())));
			}
			tld.add("tags",tag);
		}
		System.out.println(tld.toString());
	}

	private static Segment getSegment(String path) throws Exception
	{
		FileReader reader = new FileReader(FileUtils.findFile("org/ihelpuoo/weboo/tag/" + path));
		Segment tag = new CharSegment(reader);
		reader.close();
		return tag;
	}
}
